package com.leung.controller;


import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 丨一
 * @version 1.0
 * @title SeeController
 * @description:
 * @date 2025/9/27 下午2:27
 */

@RestController
@CrossOrigin
public class SseController {


    @GetMapping("/sse")
    public SseEmitter sse() {
        //创建 Sse 对象, 设置超时时间为 1 分钟
        SseEmitter emitter = new SseEmitter(60_000L);

        char[] str = "莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马, 谁怕? 一蓑烟雨任平生。".toCharArray();

        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

        AtomicInteger atomicInteger = new AtomicInteger(0);

        executor.scheduleAtFixedRate(() -> {
            try {
                emitter.send(SseEmitter.event().data(String.valueOf(str[atomicInteger.getAndIncrement()])));
                Thread.sleep(50L);
            } catch (Exception e) {
                emitter.complete();
            }
        }, 0, 300, TimeUnit.MICROSECONDS);


        emitter.onCompletion(executor::shutdown);

        return emitter;
    }

}
